package cn.iocoder.yudao.module.engine.service.core.messagestore;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.engine.enums.EnumAudioType;
import cn.iocoder.yudao.module.engine.model.context.AIMessageContext;
import cn.iocoder.yudao.module.engine.model.context.ControlEngineContext;
import cn.iocoder.yudao.module.engine.model.engine.EngineOutputData;
import cn.iocoder.yudao.module.resource.api.enums.MessageSourceTypeEnum;
import cn.iocoder.yudao.module.resource.api.model.message.AudioDataDTO;

import javax.annotation.Nullable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractMessageStore implements MessageStore {

    protected abstract void executeSaveMessages(ControlEngineContext engineContext,
                                                @Nullable AIMessageContext messageCtx,
                                                EngineOutputData.Audio audio);

    public void saveMessages(ControlEngineContext engineContext,
                             @Nullable AIMessageContext messageCtx,
                             EngineOutputData.Audio audio) {
        final boolean canSaveMessage = canSaveMessage(messageCtx, audio);
        if (!canSaveMessage) {
            return;
        }

        executeSaveMessages(engineContext, messageCtx, audio);
    }

    protected boolean canSaveMessage(AIMessageContext messageCtx, EngineOutputData.Audio audio) {
        if (StrUtil.isNotEmpty(audio.getFromMessage())
                && StrUtil.isNotEmpty(audio.getAudioDesc())
                && audio.getAudioType() == EnumAudioType.CHAT
                && isAudioCompleted(messageCtx, audio)) {
            return true;
        }
        return false;
    }

    protected boolean isAudioCompleted(AIMessageContext messageCtx, EngineOutputData.Audio audio) {
        if (messageCtx != null && audio.getMessageSendType() == MessageSourceTypeEnum.AI) {
            final List<AIMessageContext.AudioTask> audioTaskQueue = messageCtx.getAudioTaskQueue();
            for (AIMessageContext.AudioTask audioTask : audioTaskQueue) {
                if (!audioTask.isTtsDone()) {
                    return false;
                }
            }
        }
        return true;
    }

    protected List<AudioDataDTO> getAudioDataList(AIMessageContext messageCtx, EngineOutputData.Audio audio) {
        final List<AudioDataDTO> audioDataList = new ArrayList<>();

        if (messageCtx != null && (audio.getMessageSendType() == MessageSourceTypeEnum.AI || audio.getMessageSendType() == MessageSourceTypeEnum.VECTOR)) {
            final List<AIMessageContext.AudioTask> audioTaskQueue = messageCtx.getAudioTaskQueue();
            for (AIMessageContext.AudioTask audioTask : audioTaskQueue) {
                if (!audioTask.isTtsDone()) {
                    return null;
                }

                final AudioDataDTO audioData = audioTask.getAudioData();
                audioDataList.add(audioData);
            }
        }

        if (audio.getMessageSendType() == MessageSourceTypeEnum.SYSTEM) {
            final AudioDataDTO audioData = AudioDataDTO.builder()
                    .toneId(audio.getToneId())
                    .id(audio.getAudioId())
                    .sentence(audio.getAudioDesc())
                    .path(extractPathFromURL(audio.getAudioUrl()))
                    .url(audio.getAudioUrl())
                    .encryptKey(audio.getEncryptKey())
                    .build();
            audioDataList.add(audioData);
        }

        return audioDataList;
    }


    protected String getReplyText(@org.jetbrains.annotations.Nullable
                                  AIMessageContext messageCtx,
                                  EngineOutputData.Audio audio) {
        return messageCtx != null ? messageCtx.getFullReplyText() : audio.getAudioDesc();
    }

    private static String extractPathFromURL(String url) {
        try {
            URI uri = new URI(url);
            return uri.getPath(); // 获取路径部分
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null; // 解析失败时返回 null
        }
    }

}
